<template>
  <a-modal v-model:visible="visible" :footer="false" fullscreen>
    <template #title> {{ tournament.name }} 比賽賽程 </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px" @click="openAddPopup">創建賽程</a-button>
      </a-col>
    </a-row>
    <a-table
      row-key="id"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%' }"
      :columns="columns"
      :pagination="false"
      :data="data">
      <template #is_rematch="{ record }">
        {{ record.is_rematch ? '是' : '否' }}
      </template>
      <template #start_time_type="{ record }">
        {{ record.start_time_type == 1 ? '開賽前30分鐘' : '開賽前3小時' }}
      </template>
      <template #round_order="{ record }">
        {{ record.round_order }} {{ record.rematch_schedule_id ? '(重賽)' : '' }}
      </template>
      <template #match_stage="{ record }">
        {{ record.match_stage == 0 ? '其他' : '' }}
        {{ record.match_stage == 1 ? '64強賽' : '' }}
        {{ record.match_stage == 2 ? '32強賽' : '' }}
        {{ record.match_stage == 3 ? '16強賽' : '' }}
        {{ record.match_stage == 4 ? '總決賽' : '' }}
      </template>
      <template #optional="{ record }">
        <a-link v-auth="[1, 2]" @click="openEditPopup(record)">編輯</a-link>
        <a-link v-auth="[1, 2]" @click="openSchedulesPopup(record)">比賽數據</a-link>
      </template>
    </a-table>
    <a-modal
      v-model:visible="visibleAddPopup"
      :title="type == 'add' ? '添加' : '編輯'"
      width="600px"
      :ok-loading="btnLoading"
      @cancel="close"
      @before-ok="submit">
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <a-form-item label="賽程名稱" field="title">
          <a-input v-model="formData.title" placeholder="請輸入賽程名稱" />
        </a-form-item>
        <a-form-item label="賽程輪次" v-if="type == 'add' && formData.isRematch == 0" field="roundOrder">
          <a-input-number :min="1" :max="100" v-model="formData.roundOrder" placeholder="請輸入賽程輪次" />
        </a-form-item>
        <a-form-item label="前幾名可晉級" field="advancement_count">
          <a-input-number :min="1" :max="100" v-model="formData.advancement_count" placeholder="請輸入晉級最低排名" />
        </a-form-item>
        <a-form-item label="房間人數" field="entry_num">
          <a-input-number :min="1" :max="100" v-model="formData.entry_num" placeholder="請輸入房間人數" />
        </a-form-item>
        <a-form-item label="創建房間時間" field="start_time_type">
          <a-radio-group v-model="formData.start_time_type" type="button">
            <a-radio :value="1">開賽前30分鐘</a-radio>
            <a-radio :value="3">開賽前3小時</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="比賽時間" field="timeList">
          <a-range-picker
            v-model="formData.timeList"
            showTime
            :time-picker-props="{
              defaultValue: ['00:00:00', '00:00:00'],
            }"
            @change="onChange"
            style="width: 100%" />
        </a-form-item>
        <a-form-item label="比賽階段" field="match_stage">
          <a-radio-group v-model="formData.match_stage" type="button">
            <a-radio :value="0">其他</a-radio>
            <a-radio :value="1">64強賽</a-radio>
            <a-radio :value="2">32強賽</a-radio>
            <a-radio :value="3">16強賽</a-radio>
            <a-radio :value="4">總決賽</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="重賽賽程" v-if="type == 'add'" field="isRematch">
          <a-radio-group v-model="formData.isRematch" type="button">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="重賽賽程" v-if="type == 'add' && formData.isRematch" field="rematch_schedule_id">
          <a-select v-model="formData.rematch_schedule_id" placeholder="請選擇需要重賽的賽程">
            <a-option v-for="item in data" :key="item.id" :value="item.id">{{ item.title }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal title="比賽數據" v-model:visible="visibleUserPopup" width="75%" :footer="false">
      <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="24">
          <a-radio-group
            @change="
              () => {
                selectedKeys = []
                page_obj.current = 1
                page_obj.pageSize = 20
                searchGameId()
              }
            "
            type="button"
            class="mb-2"
            v-model="userPopupType">
            <a-radio value="un_group_users">未分組 ({{ userGroupObj.un_group_users_all.length }})</a-radio>
            <a-radio value="winner_group_users">勝者 ({{ userGroupObj.winner_group_users_all.length }})</a-radio>
            <a-radio value="loser_group_users">敗者 ({{ userGroupObj.loser_group_users_all.length }})</a-radio>
            <a-radio value="grouped_users">用戶分組 ({{ userGroupObj.grouped_users.length }})</a-radio>
          </a-radio-group>
          <a-button
            v-auth="[1, 2]"
            v-if="userPopupType == 'un_group_users' && !schedule.rematch_schedule_id"
            type="primary"
            style="margin: 0 10px"
            @click="suiji"
            >隨機分組</a-button
          >
          <a-button
            v-auth="[1, 2]"
            v-if="userPopupType == 'un_group_users' && schedule.rematch_schedule_id"
            type="primary"
            style="margin: 0 10px"
            @click="openRematchPopup(schedule)"
            >重賽分組</a-button
          >
          <template v-if="userPopupType == 'grouped_users'">
            <span>比賽時間</span>
            <a-date-picker
              v-model="formData2.start_time"
              show-time
              :time-picker-props="{ defaultValue: '00:00:00' }"
              format="YYYY-MM-DD HH:mm:ss" />
            <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px" @click="startTime">批量設置</a-button>
            <a-popconfirm content="確定分組完成嗎？" @before-ok="confirmGroups(record)" type="warning">
              <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px">分組完成</a-button>
            </a-popconfirm>
            <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px" @click="exportGroups">導出分組</a-button>
          </template>
          <template
            v-if="
              userPopupType == 'winner_group_users' ||
              userPopupType == 'loser_group_users' ||
              userPopupType == 'un_group_users'
            ">
            <a-input
              v-model="gameId"
              class="w-[200px] ml-2"
              @clear="searchGameId"
              placeholder="請輸入遊戲id"
              allow-clear />
            <a-button v-auth="[1, 2]" type="primary" class="ml-2" @click="searchGameId">搜索</a-button>
          </template>
        </a-col>
      </a-row>
      <a-table
        row-key="uid"
        :loading="loading"
        v-model:selectedKeys="selectedKeys"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
        :pagination="{
          'show-total': true,
          'show-jumper': true,
          'show-page-size': true,
          current: page_obj.current,
          pageSize: page_obj.pageSize,
          'page-size-options': [20, 30, 40, 50, 100],
        }"
        :row-selection="userPopupType == 'grouped_users' ? rowSelection : undefined"
        :scroll="{ x: '100%', y: '500px' }"
        :columns="
          userPopupType == 'grouped_users'
            ? columnUserGroup2
            : userPopupType == 'winner_group_users'
            ? columnUserGroup3
            : columnUserGroup
        "
        :data="userGroupObj[userPopupType]">
        <template #group_id="{ record }"> {{ record.group_title }} (第{{ record.group_rank }}名) </template>
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" v-if="userPopupType == 'grouped_users'" @click="openLookUserPopup(record)"
            >查看用戶</a-link
          >
          <a-popconfirm content="確定開啓競賽嗎？" @before-ok="openGuessStatus(record)" type="warning">
            <a-link v-auth="[1, 2]" v-if="userPopupType == 'grouped_users'" :disabled="!!record.guess_status">{{
              record.guess_status ? '已開啓' : '開啓競猜'
            }}</a-link>
          </a-popconfirm>
        </template>
        <template #optional3="{ record }">
          <a-link v-auth="[1, 2]" @click="disqualification(record)">取消資格</a-link>
        </template>
      </a-table>
    </a-modal>
    <a-modal
      :ok-loading="btnLoading"
      @cancel="closeSuiji"
      @before-ok="submitSuiji"
      v-model:visible="visibleSuijiPopup"
      width="60%">
      <a-table
        row-key="uid"
        :scroll="{ x: '100%', y: '500px' }"
        :columns="columnSuijiGroup"
        :expandable="{
          expandedRowKeys: expandedRowKeys,
        }"
        :pagination="{
          'show-total': true,
          'show-jumper': true,
          'show-page-size': true,
        }"
        @expand="handleExpand"
        :data="userGroupObj.suiji_user">
        <template #children1="{ record }">
          {{ record.children1.length }}
        </template>
        <template #expand-row="{ record }">
          <a-table
            size="mini"
            row-key="uid"
            :scroll="{ x: '100%', y: '100%' }"
            :columns="columnUserGroup4"
            :pagination="false"
            :data="record.children1">
          </a-table>
        </template>
      </a-table>
    </a-modal>
    <a-modal
      :ok-loading="btnLoading"
      v-model:visible="visibleRematchPopup"
      title="重賽分組可選擇列表"
      width="70%"
      @cancel="closeRematch"
      @before-ok="submitRematch">
      <a-table
        row-key="uid"
        :loading="loading"
        v-model:selectedKeys="selectedKeys2"
        :row-selection="rowSelection"
        :scroll="{ x: '100%', y: '500px' }"
        :columns="columnUserGroup2"
        :data="rematchList">
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" @click="openLookUserPopup(record)">查看用戶</a-link>
        </template>
      </a-table>
    </a-modal>
    <a-modal v-model:visible="visibleLookPopup" title="查看用戶" :footer="false" width="70%">
      <a-table
        :pagination="false"
        row-key="uid"
        :scroll="{ x: '100%', y: '500px' }"
        :columns="lookColumnUserGroup"
        :data="lookUserDate">
        <template #group_rank="{ record }">
          {{ record.group_rank ? `第${record.group_rank}名` : '-' }}
        </template>
        <template #invite_status="{ record }">
          <span v-if="record.invite_status == 1" class="success">邀請成功</span>
          <span v-if="record.invite_status == 2" class="warning"
            >邀請失敗{{ record.failure_reason ? `(原因：${record.failure_reason})` : '' }}</span
          >
          <span v-if="!record.invite_status" class="danger">沒開始邀請</span>
        </template>
      </a-table>
    </a-modal>
  </a-modal>
</template>
<script setup>
import { ref, reactive } from 'vue'
import tournamentApi from '@/api/tournament'
import { Message, Modal } from '@arco-design/web-vue'
const rematchList = ref([])
const selectedKeys2 = ref([])
const page_obj = ref({
  current: 1,
  pageSize: 20,
})
const pageChange = (page) => {
  page_obj.value.current = page
}
const pageSizeChange = (pageSize) => {
  page_obj.value.pageSize = pageSize
  page_obj.value.current = 1
}
const gameId = ref('')
const visibleRematchPopup = ref(false)
const openRematchPopup = async (record) => {
  closeRematch()
  loading.value = true
  const res = await tournamentApi.getTournamentStageUsers({
    tournament_id: record.tournament_id,
    schedule_id: record.rematch_schedule_id,
  })
  let list = (res.data.grouped_users || []).map((item) => {
    return {
      uid: item.group_id,
      user_id_str: item.players.map((i) => i.uid).join(','),
      ...item,
    }
  })
  rematchList.value = list.filter((item) => item.status == 2)
  for (let i = 0; i < rematchList.value.length; i++) {
    const eleI = rematchList.value[i]
    for (let j = 0; j < userGroupObj.value.grouped_users.length; j++) {
      const eleJ = userGroupObj.value.grouped_users[j]
      if (eleI.user_id_str == eleJ.user_id_str) {
        eleI.disabled = true
      } else {
        eleI.disabled = false
      }
    }
  }
  visibleRematchPopup.value = true
  loading.value = false
}
const closeRematch = () => {
  // selectedKeys2
  selectedKeys2.value = []
  loading.value = false
  visibleRematchPopup.value = false
}
const submitRematch = (done) => {
  if (!selectedKeys2.value.length) {
    done(false)
    return Message.error('請選擇數據')
  }
  let list = rematchList.value.filter((item) => selectedKeys2.value.includes(item.uid))
  Modal.open({
    title: '提示',
    content: '確定要隨機分組嗎？',
    onOk: async () => {
      await tournamentApi.createGroupsFromUsers({
        tournament_id: schedule.value.tournament_id,
        schedule_id: schedule.value.id,
        user_groups: list.map((item, index) => {
          return {
            group_number: index,
            player_uids: item.players.map((i) => i.uid),
          }
        }),
        is_rematch: schedule.value.is_rematch,
      })
      done(true)
      Message.success('隨機分組成功')
      userPopupType.value = 'suiji_user'
      openSchedulesPopup(schedule.value)
    },
    onCancel: () => {
      done(false)
    },
  })
}
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true,
}
const selectedKeys = ref([])

const formData2 = ref({
  start_time: '',
})

const visibleSuijiPopup = ref(false)
const columnSuijiGroup = [
  { title: '分組', dataIndex: 'group_name' },
  { title: '人數', dataIndex: 'children1', slotName: 'children1' },
]
const closeSuiji = () => {
  visibleSuijiPopup.value = false
}
const disqualification = async (record) => {
  Modal.open({
    title: '提示',
    content: `確定要取消【${record.group_title}】分組的【${record.game_nickname}】比賽資格嗎？`,
    onOk: async () => {
      await tournamentApi.disqualification({
        groupId: record.group_id,
        uid: record.uid,
      })
      Message.success('取消成功')
      openSchedulesPopup(schedule.value)
    },
    onCancel: () => {},
  })
}
const submitSuiji = (done) => {
  Modal.open({
    title: '提示',
    content: '確定要隨機分組嗎？',
    onOk: async () => {
      await tournamentApi.createGroupsFromUsers({
        tournament_id: schedule.value.tournament_id,
        schedule_id: schedule.value.id,
        user_groups: userGroupObj.value.suiji_user.map((item) => {
          return {
            group_number: item.group_number,
            player_uids: item.children1.map((item) => {
              return item.uid
            }),
          }
        }),
        is_rematch: schedule.value.is_rematch,
      })
      done(true)
      Message.success('隨機分組成功')
      userPopupType.value = 'suiji_user'
      openSchedulesPopup(schedule.value)
    },
    onCancel: () => {
      done(false)
    },
  })
}
const lookUserDate = ref([])
const lookColumnUserGroup = [
  { title: 'uid', dataIndex: 'uid' },
  { title: '名稱', dataIndex: 'game_nickname' },
  { title: '稱號', dataIndex: 'title' },
  { title: '遊戲id', dataIndex: 'game_id' },
  { title: '排名', dataIndex: 'group_rank', slotName: 'group_rank', align: 'center' },
  { title: '邀請狀態', dataIndex: 'invite_status', slotName: 'invite_status', align: 'center' },
  { title: '社團', dataIndex: 'club_name' },
]
const visibleLookPopup = ref(false)
const openLookUserPopup = (record) => {
  visibleLookPopup.value = true
  lookUserDate.value = record.players
}
const openGuessStatus = async (record) => {
  try {
    await tournamentApi.openGuessStatus({
      groupId: record.group_id,
      guessStatus: 1,
    })
    Message.success('開啓競賽成功')
    record.guess_status = 1
    record.guess_status_name = '競猜中'
  } catch (error) {
    return false
  }
}

const expandedRowKeys = ref([])
const handleExpand = (rowKey, checked, a, b, c) => {
  expandedRowKeys.value.includes(rowKey) ? expandedRowKeys.value.splice(0, 1) : expandedRowKeys.value.push(rowKey)
}

const visibleUserPopup = ref(false)
const userGroupObj = ref({
  un_group_users: [],
  un_group_users_all: [],
  winner_group_users: [],
  winner_group_users_all: [],
  loser_group_users_all: [],
  loser_group_users: [],
  grouped_users: [],
  suiji_user: [],
  stage_info: {},
})
const searchGameId = () => {
  if (userPopupType.value == 'winner_group_users') {
    userGroupObj.value.winner_group_users = userGroupObj.value.winner_group_users_all.filter((item) =>
      item.game_id.includes(gameId.value)
    )
  } else if (userPopupType.value == 'loser_group_users') {
    userGroupObj.value.loser_group_users = userGroupObj.value.loser_group_users_all.filter((item) =>
      item.game_id.includes(gameId.value)
    )
  } else if (userPopupType.value == 'un_group_users') {
    userGroupObj.value.un_group_users = userGroupObj.value.un_group_users_all.filter((item) =>
      item.game_id.includes(gameId.value)
    )
  }
  gameId.value = ''
}
const userPopupType = ref('winner_group_users')
const columnUserGroup = [
  { title: '序號', dataIndex: 'index', width: 60, align: 'center' },
  { title: 'uid', dataIndex: 'uid' },
  { title: '名稱', dataIndex: 'game_nickname' },
  { title: '稱號', dataIndex: 'title' },
  { title: '遊戲id', dataIndex: 'game_id' },
  { title: '社團', dataIndex: 'club_name' },
]
const columnUserGroup3 = [
  {
    title: '序號',
    dataIndex: 'index',
    width: 60,
    align: 'center',
  },
  { title: 'uid', dataIndex: 'uid' },
  { title: '名稱', dataIndex: 'game_nickname' },
  { title: '稱號', dataIndex: 'title' },
  { title: '社團', dataIndex: 'club_name' },
  { title: '組名', dataIndex: 'group_id', slotName: 'group_id' },
  { title: '遊戲id', dataIndex: 'game_id' },
  { title: '操作', slotName: 'optional3' },
]
const columnUserGroup2 = [
  { title: '分組名稱', dataIndex: 'group_name' },
  {
    title: '房間號',
    dataIndex: 'room_code',
    render: ({ record }) => {
      return record.room_code || '-'
    },
  },

  {
    title: '開始時間',
    dataIndex: 'start_time',
    width: 170,
    render: ({ record }) => {
      return record.start_time || '-'
    },
  },
  { title: '競賽狀態', dataIndex: 'guess_status_name' },
  { title: '狀態', dataIndex: 'status_name' },
  { title: '裁判', dataIndex: 'judge_nickname' },
  { title: '操作', slotName: 'optional', width: 170 },
]
const columnUserGroup4 = [
  { title: 'uid', dataIndex: 'uid' },
  { title: '名稱', dataIndex: 'game_nickname' },
  { title: '稱號', dataIndex: 'title' },
  { title: '遊戲id', dataIndex: 'game_id' },
  { title: '社團', dataIndex: 'club_name' },
]
const startTime = () => {
  if (!selectedKeys.value.length) return Message.error('請選擇數據')
  if (!formData2.value.start_time) return Message.error('請選擇時間')
  Modal.open({
    title: '提示',
    content: '確定要批量設置開始時間嗎？',
    onOk: async () => {
      await tournamentApi.updateStartTime({
        group_ids: selectedKeys.value,
        start_time: formData2.value.start_time,
      })
      formData2.value.start_time = ''
      selectedKeys.value = []
      Message.success(`設置成功`)
      userPopupType.value = 'suiji_user'
      openSchedulesPopup(schedule.value)
    },
    onCancel: () => {},
  })
}
const suiji = () => {
  let list = userGroupObj.value.un_group_users
  if (!list.length) return Message.error('暫無數據')
  let stage_info = userGroupObj.value.stage_info
  // round_order
  // 複製原始數組並隨機打亂順序
  const shuffled = [...list]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  let length = shuffled.length
  let fenzushuliang = 0
  if (length > 4096) {
    fenzushuliang = Math.ceil(length / 16)
  } else if (length <= 4096 && length > 1024) {
    fenzushuliang = 256
  } else if (length <= 1024 && length > 256) {
    fenzushuliang = 64
  } else if (length <= 256 && length > 64) {
    fenzushuliang = 16
  } else if (length <= 64 && length > 32) {
    fenzushuliang = 4
  } else if (length <= 32 && length > 16) {
    fenzushuliang = 2
  } else if (length <= 16 && length > 8) {
    fenzushuliang = 1
  } else {
    fenzushuliang = 1
  }
  let num = Math.floor(length / fenzushuliang)
  let extra = length % fenzushuliang
  // 將打亂後的數組分割成每組最多16項的子數組
  const grouped = []
  for (let i = 0; i < fenzushuliang; i++) {
    const start = i < extra ? i * (num + 1) : extra * (num + 1) + (i - extra) * num
    let arr = shuffled.slice(start, start + (i < extra ? num + 1 : num))
    grouped.push({
      uid: i + 1,
      children1: arr,
      group_number: i + 1,
      group_name: `第${i + 1}組`,
    })
  }

  userGroupObj.value.suiji_user = grouped
  visibleSuijiPopup.value = true
}
const schedule = ref({})
const exportGroups = async () => {
  if (!selectedKeys.value.length) return Message.error('請選擇數據')
  loading.value = true
  try {
    const data = await tournamentApi.exportGroups({
      groupIds: selectedKeys.value,
    })
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'exported_data.csv'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}
const confirmGroups = async () => {
  try {
    await tournamentApi.confirmGroups({
      scheduleId: schedule.value.id,
    })
    Message.success(`操作成功！`)
    openSchedulesPopup(schedule.value)
  } catch (error) {
    return false
  }
}
const openSchedulesPopup = async (record) => {
  loading.value = true
  page_obj.value.current = 1
  page_obj.value.pageSize = 20
  if (userPopupType.value == 'suiji_user') {
    userPopupType.value = 'grouped_users'
  }
  schedule.value = record
  const res = await tournamentApi.getTournamentStageUsers({
    tournament_id: record.tournament_id,
    schedule_id: record.id,
  })
  res.data.winner_group_users.forEach((item, index) => {
    item.index = index + 1
  })
  res.data.loser_group_users.forEach((item, index) => {
    item.index = index + 1
  })
  res.data.un_group_users.forEach((item, index) => {
    item.index = index + 1
  })
  userGroupObj.value.un_group_users = res.data.un_group_users || []
  userGroupObj.value.un_group_users_all = res.data.un_group_users || []
  userGroupObj.value.winner_group_users = res.data.winner_group_users || []
  userGroupObj.value.winner_group_users_all = res.data.winner_group_users || []
  userGroupObj.value.loser_group_users = res.data.loser_group_users || []
  userGroupObj.value.loser_group_users_all = res.data.loser_group_users || []
  userGroupObj.value.grouped_users = (res.data.grouped_users || []).map((item) => {
    return {
      uid: item.group_id,
      user_id_str: item.players.map((i) => i.uid).join(','),
      ...item,
    }
  })
  userGroupObj.value.stage_info = res.data.stage_info || {}
  visibleUserPopup.value = true
  page_obj.value.current = 1
  loading.value = false
}

const visible = ref(false)
const loading = ref(false)

const type = ref('add')
const visibleAddPopup = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)
const formData = ref({
  title: '',
  roundOrder: 1,
  isRematch: 0,
  rematch_schedule_id: '',
  entry_num: 16,
  start_time_type: 1,
  match_stage: 0,
  start_time: '',
  end_time: '',
  timeList: [],
  advancement_count: 4,
})
const rules = [
  {
    title: [{ required: true, message: '請輸入賽程名稱' }],
    roundOrder: [{ required: true, message: '請輸入賽程輪次' }],
    timeList: [{ required: true, message: '請選擇比賽時間' }],
  },
]
const openEditPopup = (record) => {
  type.value = 'edit'
  formData.value = {
    id: record.id,
    title: record.title,
    roundOrder: record.round_order,
    match_stage: record.match_stage,
    isRematch: record.is_rematch,
    rematch_schedule_id: record.rematch_schedule_id || '',
    start_time_type: record.start_time_type,
    entry_num: record.entry_num,
    start_time: record.start_time,
    end_time: record.end_time,
    timeList: [record.start_time, record.end_time],
    advancement_count: record.advancement_count,
  }
  visibleAddPopup.value = true
}
const openAddPopup = () => {
  type.value = 'add'
  formData.value = {
    title: '',
    roundOrder: 1,
    match_stage: 0,
    isRematch: 0,
    rematch_schedule_id: '',
    entry_num: 16,
    start_time_type: 1,
    start_time: '',
    end_time: '',
    timeList: [],
    advancement_count: 4,
  }
  visibleAddPopup.value = true
}
const close = () => {
  visibleAddPopup.value = false
  btnLoading.value = false
}
const submit = async (done) => {
  if (formData.value.advancement_count >= formData.value.entry_num) {
    Message.error('晉級人數不能大於等於參賽人數')
    return done(false)
  }
  let obj = data.value.find((item) => item.id === formData.value.rematch_schedule_id)
  const validate = await formRef.value?.validate()
  if (validate) return done(false)
  if (type.value === 'add') {
    try {
      await tournamentApi.createTournamentSchedules({
        title: formData.value.title,
        tournamentId: tournament.value.id,
        roundOrder: formData.value.isRematch ? obj.round_order : formData.value.roundOrder,
        match_stage: formData.value.match_stage,
        isRematch: formData.value.isRematch,
        rematch_schedule_id: formData.value.isRematch ? formData.value.rematch_schedule_id : '',
        entry_num: formData.value.entry_num,
        start_time_type: formData.value.start_time_type,
        start_time: formData.value.start_time,
        end_time: formData.value.end_time,
        advancement_count: formData.value.advancement_count,
      })
      close()
      Message.success(`添加成功！`)
      open(tournament.value)
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  } else {
    try {
      await tournamentApi.updateTournamentSchedules({
        id: formData.value.id,
        title: formData.value.title,
        tournamentId: tournament.value.id,
        roundOrder: formData.value.roundOrder,
        match_stage: formData.value.match_stage,
        isRematch: formData.value.isRematch,
        rematch_schedule_id: formData.value.rematch_schedule_id,
        entry_num: formData.value.entry_num,
        start_time_type: formData.value.start_time_type,
        start_time: formData.value.start_time,
        end_time: formData.value.end_time,
        advancement_count: formData.value.advancement_count,
      })
      close()
      Message.success(`修改成功！`)
      open(tournament.value)
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  }
}
const onChange = (dateString) => {
  if (dateString) {
    formData.value.start_time = dateString[0]
    formData.value.end_time = dateString[1]
  } else {
    formData.value.start_time = ''
    formData.value.end_time = ''
  }
}

const tournament = ref({})
const data = ref([])
const open = async (item) => {
  tournament.value = item
  try {
    loading.value = true
    const res = await tournamentApi.getTournamentSchedules(item.id)
    data.value = res.data
    visible.value = true
    loading.value = false
    return Promise.resolve()
  } catch (error) {
    return Promise.resolve()
  }
}
const columns = ref([
  {
    title: '賽程名稱',
    dataIndex: 'title',
  },
  {
    title: '賽程階段',
    dataIndex: 'match_stage',
    slotName: 'match_stage',
    align: 'center',
  },
  {
    title: '房間人數',
    dataIndex: 'entry_num',
    align: 'center',
    width: 100,
  },
  {
    title: '創建房間時間',
    dataIndex: 'start_time_type',
    slotName: 'start_time_type',
    width: 140,
  },
  {
    title: '賽程輪次',
    dataIndex: 'round_order',
    slotName: 'round_order',
    align: 'center',
    width: 100,
  },
  {
    title: '最低晉級排名',
    dataIndex: 'advancement_count',
    align: 'center',
    width: 120,
  },
  {
    title: '是否是重賽',
    dataIndex: 'is_rematch',
    slotName: 'is_rematch',
    align: 'center',
  },
  {
    title: '賽程開始時間',
    dataIndex: 'start_time',
    width: 170,
  },
  {
    title: '賽程結束時間',
    dataIndex: 'end_time',
    width: 170,
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 170,
  },
])
defineExpose({
  open,
})
</script>
